<template>
  <el-input v-model="val">
    <template slot="append">
      <el-upload :http-request="upload" name="img" :before-upload="beforeUpload" :show-file-list="false" action="">
        <el-button>上传</el-button>
      </el-upload>
    </template>
  </el-input>
</template>
<script>
import { imageUpload } from '@/api/public'

export default {
  name: 'InputUpload',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      val: this.value
    }
  },
  methods: {
    // 图片上传
    upload(param) {
      var form = new FormData()
      form.append(param.filename, param.file)
      imageUpload(form).then(res => {
        if (res.status === 200) {
          this.val = res.data.path
          this.$emit('input', this.val)
          this.$message.success('上传成功')
        } else {
          this.$message.error(res.message)
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    beforeUpload(file) {
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.name)) {
        this.$message.error('上传图片只能是、jpg、png、jpeg格式!')
        return false
      }
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
    }
  }
}
</script>
